package com.own.core.html.component;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.wicket.extensions.markup.html.repeater.data.sort.SortOrder;
import org.apache.wicket.extensions.markup.html.repeater.util.SortParam;
import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider;
import org.apache.wicket.model.IModel;

import com.own.core.object.Dao;
import com.own.core.object.admin.User;
import com.own.core.operation.DbOperation;

/**
 * implementation of IDataProvider for contacts that keeps track of sort
 * information
 * 
 * @author igor
 * 
 */
public class OwnSortableDaoProvider extends SortableDataProvider {

	private Map filterMap;
	private Class cls;
	String loadQuery;


	public OwnSortableDaoProvider(Map filterMap, Class cls) {
		// set default sort
		setSort("id", SortOrder.ASCENDING);
		this.filterMap = filterMap;
		this.cls = cls;
	}

	public OwnSortableDaoProvider(String loadQuery,Map filterMap) {
		// set default sort
		setSort("id", SortOrder.ASCENDING);
		this.loadQuery = loadQuery;
		this.filterMap = filterMap;
	}

	/**
	 * @see org.apache.wicket.markup.repeater.data.IDataProvider#iterator(int,
	 *      int)
	 */
	public Iterator iterator(int first, int count) {
		SortParam sort = getSort();
		if (loadQuery != null && !"".equals(loadQuery)) {
			return DbOperation
					.getME()
					.executeNamedQuery(loadQuery, filterMap).iterator();
		} else {
			return DbOperation
					.getME()
					.listSortedAll(cls, filterMap, sort.getProperty(),
							sort.isAscending(), first, count).iterator();
		}
	}

	/**
	 * @see org.apache.wicket.markup.repeater.data.IDataProvider#size()
	 */
	public int size() {
		if (loadQuery != null && !"".equals(loadQuery)) {
			
			return DbOperation
					.getME()
					.executeNamedQuery(loadQuery, filterMap).size();
		}else{
			return (int) DbOperation.getME().countAll(cls);	
		}
		
	}

	/**
	 * @see org.apache.wicket.markup.repeater.data.IDataProvider#model(java.lang.Object)
	 */
	public IModel model(Object object) {
		return new DetachableDaoModel((Dao) object);
	}

}